﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;
using System.Web.Mvc;
using System.Xml.Linq;
using YYS;
using YYS.Controllers;
using HttpPostAttribute = System.Web.Http.HttpPostAttribute;

namespace YYS.Controllers
{
    public partial class wxController : ControlerEx
    {
        #region 媒体集
        Dictionary<string, object> _TomediaList(System.Data.SqlClient.SqlDataReader sdr)
        {
            var dic = new Dictionary<string, string>()
            {

                ["FnMI_ID"] = "miId",
                ["FnMI_Type"] = "FnMI_Type",
                ["FsMI_Title"] = "miTitle",
                ["FsMI_Duration"] = "miDuration",
                ["FsMI_ImgBase64"] = "miImgBase64",
                ["FsMI_ImgUrl"] = "miImgUrl",
                ["FsMI_ThumbImgURL"] = "miThumbImgURL",
                ["FsMI_URL"] = "miUrl",
                ["FsMI_Key"] = "miKey",
                ["FsMI_GroupKey"] = "miGroupKey",
                ["FsMI_Size"] = "miSize",
                ["FsMI_Desc"] = "miDesc"
            };
            var data = sdr.xToDictionary(dic, exclude: null, formater: (key, value, _this) =>
            {
                return value;
            });
            return data;
        }
        class mediaList
        {
            public int miId { get; set; }
            public int miIndex { get; set; }
            public int miType { get; set; }
            public string miTitle { get; set; }
            public string miUrl { get; set; }
            public string miSize { get; set; }
            public string miDuration { get; set; }
            public string miBase64 { get; set; }
            public string miImgUrl { get; set; }
            public string miDesc { get; set; }
        }
        [HttpPost]
        [v3Authorize(accessId = 401 | 402)]
        public JsonResult mediaInfoSave()
        {
            var miGroupKey = Request.Form["miGroupKey"].xTrim();
            var mediaList = Request.Form["mediaList"].xTrim().xUrlDecode();
            string xml = null;
            if (mediaList.Length > 0)
            {
                XElement xel = null;
                try
                {
                    var json = mediaList.xConvertJsonToObject<List<mediaList>>();
                    xel = new XElement("xml");
                    foreach (var x in json)
                    {
                        xel.Add(new XElement("x"
                            , new XElement("miId", x.miId)
                            , new XElement("miType", x.miType)
                            , new XElement("miTitle", x.miTitle)
                            , new XElement("miUrl", x.miUrl)
                            , new XElement("miSize", x.miSize)
                            , new XElement("miDuration", x.miDuration)
                            , new XElement("miBase64", x.miBase64)
                            , new XElement("miImgUrl", x.miImgUrl)
                            , new XElement("miDesc", x.miDesc)
                        ));
                    }
                }
                catch
                {
                    return backJson(1, "参数解析异常.mediaList");
                }
                if (xel != null) xml = xel.ToString(SaveOptions.DisableFormatting);
            };
            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.Exec, DefaultValue.DataBase);
            db.CmdText = "PR_PRC_MediaInfoSave";
            db.IsProc = true;
            db.AddParameter("@FsMI_GroupKey", SqlDbType.VarChar, miGroupKey, 128);
            db.AddParameter("@mediaList", SqlDbType.NVarChar, xml, -1);
            db.NeedOutError = true;
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            return backJson(0, null);
        }
        [HttpPost]
        [v3Authorize(accessId = 401 | 402)]
        public JsonResult mediaInfoList()
        {
            var aResult = new ResultObj<object>();
            var list = new List<object>();
            var miGroupKey = Request.Form["miGroupKey"].xTrim();
            var pageIndex = Request.Form["pageIndex"].xTo<int>();//页码
            var pageSize = Request.Form["pageSize"].xTo<int>();//每页记录数
            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.WhileRead, DefaultValue.DataBase);
            db.CmdText = "PR_PRC_MediaInfoList";
            db.IsProc = true;
            db.AddParameter("@FsMI_GroupKey", SqlDbType.VarChar, miGroupKey, 128);
            db.AddParameter("@PageIndex", System.Data.SqlDbType.Int, pageIndex, parameterDirection: System.Data.ParameterDirection.InputOutput);
            db.AddParameter("@PageSize", System.Data.SqlDbType.Int, pageSize, parameterDirection: System.Data.ParameterDirection.InputOutput);
            db.AddParameter("@RowCount", System.Data.SqlDbType.Int, 0, parameterDirection: System.Data.ParameterDirection.Output);
            db.NeedOutError = true;
            db.FuncRead = sdr =>
            {
                list.Add(_TomediaList(sdr));
            };
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            aResult.PageSize = db.OutParameters["PageSize"].xTo<int>();
            aResult.PageIndex = db.OutParameters["PageIndex"].xTo<int>();
            aResult.RowCount = db.OutParameters["RowCount"].xTo<int>();
            return backJson(0, null, new
            {
                pageIndex = aResult.PageIndex,
                pageSize = aResult.PageSize,
                rowCount = aResult.RowCount,
                list = list
            });
        }
        [HttpPost]
        public JsonResult mediaInfoOne()
        {
            object data = null;
            var miGroupKey = Request.Form["miGroupKey"].xTrim();
            if (string.IsNullOrWhiteSpace(miGroupKey)) return backJson(1, "缺少【媒体组】参数");
            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.WhileRead, DefaultValue.DataBase);
            db.CmdText = "SELECT TOP 1 * FROM dbo.MediaInfo WHERE FnMI_Type=4 AND FsMI_GroupKey=@FsMI_GroupKey ORDER BY NEWID();";
            db.IsProc = false;
            db.AddParameter("@FsMI_GroupKey", SqlDbType.VarChar, miGroupKey, 128);
            db.NeedOutError = true;
            db.FuncRead = sdr =>
            {
                data = _TomediaList(sdr);
            };
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            return backJson(0, null, data);
        }
        #endregion 图片集

        #region 帮助文档
        /// <summary>
        /// 系统使用说明列表
        /// </summary>
        /// <returns></returns> 

        static Dictionary<string, object> _ToHelperDoc(System.Data.SqlClient.SqlDataReader sdr)
        {
            var _helperDoc = new Dictionary<string, string>()
            {
                { "FnHD_ID","hdId" } ,{ "FnHD_PID","hdPid" }
                ,{ "FnHD_Type","hdType" } ,{ "FsHD_Title","hdTitle" },{ "FsMI_Key","miKey" } ,{ "FdHD_MakeTime","makeTime" }
                ,{ "FdHD_CreateTime","creteTime" } ,{ "FnHD_Status","hdStatus" } ,{ "FnOI_ID","oiId"},{ "FsOI_Name","oiName" },{ "MediaList","mediaList" },{"share","share"}
            };

            return sdr.xToDictionary(_helperDoc, null, formater: (key, value, _this) =>
            {
                if (key == "FdHD_CreateTime" || key == "FdHD_MakeTime")
                {
                    return value.xFormatDateTime("yyyy-MM-dd HH:mm:ss");
                }
                if (key == "MediaList")
                {
                    if (value.xTrim().xIsNullOrEmpty()) return new object[] { };
                    System.Xml.Linq.XElement xel;
                    try
                    {
                        xel = value.xTrim().ConvertToXElement();
                    }
                    catch
                    {
                        return new object[] { };
                    }

                    return xel.Elements().Select(x => new mediaList
                    {
                        miId = x.xXmlValue<int>("FnMI_ID"),
                        miIndex = x.xXmlValue<int>("FnMI_Index"),
                        miType = x.xXmlValue<int>("FnMI_Type"),
                        miSize = x.xXmlValue<string>("FsMI_Size"),
                        miDuration = x.xXmlValue<string>("FsMI_Duration"),
                        miTitle = x.xXmlValue<string>("FsMI_Title"),
                        miUrl = x.xXmlValue<string>("FsMI_Url")
                    });
                }
                return value;
            });
        }
        [HttpPost]
        [v3Authorize()]
        public JsonResult HelperDocList()
        {
            var id = Request.Form["id"].xTo<int>();
            var optor = Request.v3UnifiedUser();
            var max = optor.cando(30902) ? 1 : 0;
            var list = new List<object>();
            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.WhileRead, DefaultValue.DataBase);
            db.CmdText = "SELECT FnHD_ID, FnHD_PID ,FnHD_Type, FsHD_Title, FdHD_CreateTime, FnHD_Status, FsMI_Key, FnOI_ID, FsOI_Name, FdHD_MakeTime,share FROM dbo.TA_O_HelperDoc WHERE  (share=0 OR (share=1 AND FnOI_ID=@oiId) OR @max=1) AND FnHD_PID=@id";
            db.AddParameter("@oiId", SqlDbType.NVarChar, optor.openId, 50);
            db.AddParameter("@id", SqlDbType.BigInt, id);
            db.AddParameter("@max", SqlDbType.Int, max);
            db.NeedOutError = true;
            db.FuncRead = sdr =>
            {
                var obj = _ToHelperDoc(sdr);
                list.Add(obj);
            };
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            return backJson(0, null, list);
        }

        #endregion 帮助文档

        #region 组装登录的key
        [HttpPost]
        [v3Authorize()]
        public JsonResult getLoginKey()
        {
            var optor = Request.v3UnifiedUser();
            var obj = new
            {
                account = optor.account,
                pwd = optor.pwd,
                time = DateTime.Now
            };
            var key = obj.xConvertObjectToJson(false).xAESEncrypt(YYS.DefaultValue.EnvAESKey).xToSafeBase64();//base64 加密转 URL安全base64safaBase64
            return backJson(0, null, key);
        }
        #endregion

        #region 公告 
        Dictionary<string, object> _Tonotice(System.Data.SqlClient.SqlDataReader sdr)
        {
            var dic = new Dictionary<string, string>()
            {

                ["id"] = "id",
                ["title"] = "title",
                ["msg_key"] = "msg_key",
                ["msg"] = "msg",
                ["beginTime"] = "beginTime",
                ["endTime"] = "endTime",
                ["time"] = "time",
                ["status"] = "status",
                ["openId"] = "openId",
                ["scrollable"] = "scrollable",
                ["closeable"] = "closeable",
                ["speed"] = "speed",

            };
            return sdr.xToDictionary(dic, exclude: null, formater: (key, value, _this) =>
            {
                if (key == "time" || key == "endTime" || key == "beginTime")
                {
                    return value.xFormatDateTime("yyyy-MM-dd HH:mm:ss");
                };
                return value;
            });
        }
        [HttpPost]
        [v3Authorize()]
        public JsonResult noticeOne()
        {
            object data = null;
            var optor = Request.v3UnifiedUser();
            if (!optor.cando(308)) return backJson(0, null, data);
            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.IfRead, DefaultValue.DataBase);
            db.CmdText = "SELECT TOP 1 id,title,msg_key,msg,beginTime,endTime,status,openId,time,scrollable,closeable,speed FROM dbo.notice WHERE status<2 AND(GETDATE() BETWEEN beginTime AND endTime) ORDER BY time DESC";
            db.IsProc = false;
            db.NeedOutError = true;
            db.FuncRead = sdr =>
            {
                data = _Tonotice(sdr);
            };
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            return backJson(0, null, data);
        }
        #endregion 公告

        #region 微信 订阅消息 模版ID
        [HttpPost]
        public ActionResult wxTemplateIdlist()
        {
            var list = new List<object>();
            //list.Add(new
            //{
            //    id = "o8Pm8tarzotnvg2Ik2ylj0BlXWrN-t-80tGQL5ziAyg",
            //    name = "课程提醒"
            //});
            list.Add(new
            {
                id = "o8Pm8tarzotnvg2Ik2ylj5JSjdrIt8ew9m8r_cXVk2Y",
                name = "日程提醒"
            });
            list.Add(new
            {
                id = "ZldooaxafKj5aZn9bzflwJovQ0fG0_Zpfk1EY13bEqo",
                name = "版本更新通知"
            });
            return backJson(0, "", list);
        }
        #endregion

        #region 微信通知
        #region 类
        public class MessageTemplateSendDataContentDto
        {
            /// <summary>
            /// 文本内容
            /// </summary>
            public string value { get; set; }

            /// <summary>
            /// 文本颜色
            /// </summary>
            public string color { get; set; }
        }
        public class MessageTemplateSendDataDto
        {            
            public MessageTemplateSendDataContentDto character_string1 { get; set; }            
            public MessageTemplateSendDataContentDto thing1 { get; set; }
            public MessageTemplateSendDataContentDto thing2 { get; set; }
            public MessageTemplateSendDataContentDto thing3 { get; set; }
            public MessageTemplateSendDataContentDto thing4 { get; set; }
            public MessageTemplateSendDataContentDto thing5 { get; set; }
            public MessageTemplateSendDataContentDto thing6 { get; set; }
            public MessageTemplateSendDataContentDto time3 { get; set; }
            public MessageTemplateSendDataContentDto time8 { get; set; }
            public MessageTemplateSendDataContentDto thing11 { get; set; }

            public MessageTemplateSendDataContentDto remark { get; set; }
        }
        public class MessageTemplateSendDto
        {
            /// <summary>
            /// 必填
            /// 接收者openid
            /// </summary>
            public string touser { get; set; }

            /// <summary>
            /// 必填
            /// 模板ID
            /// </summary>
            public string template_id { get; set; }

            /// <summary>
            /// 模板跳转链接
            /// </summary>
            public string page { get; set; }

            /// <summary>
            /// 跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
            /// </summary>
            public string miniprogram_state { get; set; }

            /// <summary>
            /// 必填
            /// 模板数据
            /// </summary>
            public MessageTemplateSendDataDto data { get; set; }

            /// <summary>
            /// 模板内容字体颜色，不填默认为黑色
            /// </summary>
            public string color { get; set; }

            /// <summary>
            /// 防重入id。对于同一个openid + client_msg_id, 只发送一条消息,10分钟有效,超过10分钟不保证效果。若无防重入需求，可不填
            /// </summary>
            public string client_msg_id { get; set; }
        }
        public class userMsg
        {
            public string templateId { get; set; }
            public string name { get; set; }
            public string openId { get; set; }
            public int errcode { get; set; }
            public string errmsg { get; set; }
            public string poster { get; set; }
        }
        #endregion
        /// <summary>
        /// 微信更新提醒
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult wxUpdateSend()
        {
            var openIdList = Request.Form["openIdList"].xTrim().xUrlDecode();
            var url = $"https://api.weixin.qq.com/cgi-bin/token";
            string postData = @"appid={0}&secret={1}&grant_type={2}".jFormat(DefaultValue.AppID, DefaultValue.AppSecret, "client_credential");
            var data = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(Xcode.API.xHttpPostByWebRequest(url, postData, Xcode.ContentType.Form), new { access_token = "", errcode = 0, errmsg = "" });
            if (data.errcode > 0) return backJson(1, data.errmsg);
            var list = new List<object>();
            try
            {
                var json = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(openIdList, new[] { new { openId = "", uiName = "" } });
                foreach (var x in json)
                {
                    var state = "";
                    string openId = x.openId, redirect_url = $"pages/index/index?user={x.openId}&state={state}";

                    //构建请求数据对象
                    MessageTemplateSendDto mts = new MessageTemplateSendDto
                    {//必填 接收者openid
                        touser = x.openId,
                        //必填 模板ID
                        template_id = "ZldooaxafKj5aZn9bzflwJovQ0fG0_Zpfk1EY13bEqo",
                        page = $"pages/index/index?user={x.openId}&state={state}",
                        miniprogram_state = "formal",
                                                     //必填 模板数据
                    data = new MessageTemplateSendDataDto
                        {
                            character_string1 = new MessageTemplateSendDataContentDto()
                            {
                                value = "3.0.4",
                                color = "#173177"
                            },
                            thing2 = new MessageTemplateSendDataContentDto()
                            {
                                value = "新增订阅消息功能",
                                color = "#173177"
                            }                            
                        }
                    };
                    string poster = JsonConvert.SerializeObject(mts);

                   
                    var send = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(HttpPostByWebRequest("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + data.access_token, poster, Xcode.ContentType.Json, System.Text.Encoding.UTF8), new { access_token = "", errcode = 0, errmsg = "" });
                    if (send.errcode > 0) list.Add(new
                    {
                        name = x.uiName,
                        openId = x.openId,
                        errcode = send.errcode,
                        errmsg = send.errmsg,
                        poster= poster
                    });
                };
            }
            catch(Exception ex)
            {
                return backJson(1, "解析出错："+ex.Message, openIdList);
            }  
            return backJson(0, null,list);
        }
        [HttpPost]
        public ActionResult wxCSSend()
        {
            var sendData = Request.Form["data"].xTrim();
            var url = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={YYS.DefaultValue.AppID_WXCS}&secret={YYS.DefaultValue.AppSecret_WXCS}";
            var data = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(HttpGetByWebRequest(url, System.Text.Encoding.UTF8, 100), new { access_token = "", errcode = 0, errmsg = "" });
            if (data.errcode > 0) return backJson(1, "token获取失败："+data.errmsg);

            string open_id = "o9tiy6R5of_mjjydo23Q55aQp5Do", redirect_url= "http://yangys.icu/yys/wx/go?state=userinfo&userid=o9tiy6R5of_mjjydo23Q55aQp5Do", msg_title= "template_id", template_id= "AqD1M_-N9KwrSNOs5ZAym97zGTd8aCCLG1fvvHEvgR8";
            string poster = "{\"touser\": \"" + open_id + "\",\"template_id\":\""+template_id+"\", "
                + "\"url\":\"" + redirect_url + "\","
                + "\"data\":{\"msg\":{\"value\":\"" + msg_title + "\",\"color\":\"#ff0000\"},"
                          + "\"time\":{\"value\":\"" + DateTime.Now.ToString("yyyyMMddHHmmssms") + "\",\"color\":\"#ff0000\"}"
                + " } }";
            var send = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(Xcode.API.xHttpPostByWebRequest("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + data.access_token, poster, Xcode.ContentType.Json), new { errcode = 0, errmsg = ""});
            if (data.errcode > 0) return backJson(1, "发送失败："+data.errmsg);
            return backJson(0, null, new {
                poster= poster,
                send=send
            });
        }

        /// <summary>
        /// 信息发布提醒
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult wxXinxiSend()
        {
            var openIdList = Request.Form["openIdList"].xTrim().xUrlDecode();            
            var url = $"https://api.weixin.qq.com/cgi-bin/token";
            string postData = @"appid={0}&secret={1}&grant_type={2}".jFormat(DefaultValue.AppID, DefaultValue.AppSecret, "client_credential");
            var data = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(Xcode.API.xHttpPostByWebRequest(url, postData, Xcode.ContentType.Form), new { access_token = "", errcode = 0, errmsg = "" });
            if (data.errcode > 0) return backJson(1, data.errmsg);
            var list = new List<object>();
            try
            {
                var json = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(openIdList, new[] { new { openId = "", uiName = "" } });
                foreach (var x in json)
                {
                    var state = "fingerPrint";
                    
                    //构建请求数据对象
                    MessageTemplateSendDto mts = new MessageTemplateSendDto
                    {//必填 接收者openid
                        touser = x.openId,
                        //必填 模板ID
                        template_id = "EqyueRH31b-IdrPZ17iO9yxwEp4ps2FMfj9KocHv3Y8",
                        page = $"pages/index/index?user={x.openId}&state={state}",
                        miniprogram_state = "formal",
                        //必填 模板数据
                        data = new MessageTemplateSendDataDto
                        {
                            thing3 = new MessageTemplateSendDataContentDto()
                            {
                                value = "日程提醒",
                                color = "#173177"
                            },
                            thing4 = new MessageTemplateSendDataContentDto()
                            {
                                value = "来自“yangys”",
                                color = "#173177"
                            },
                            thing6 = new MessageTemplateSendDataContentDto()
                            {
                                value = "yangys",
                                color = "#173177"
                            },
                            time8 = new MessageTemplateSendDataContentDto()
                            {
                                value = DateTime.Now.ToString(),
                                color = "#173177"
                            },
                            thing11 = new MessageTemplateSendDataContentDto()
                            {
                                value = "今天天气很好",
                                color = "#173177"
                            }
                        }
                    };
                    string poster = JsonConvert.SerializeObject(mts);


                    var send = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(HttpPostByWebRequest("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + data.access_token, poster, Xcode.ContentType.Json, System.Text.Encoding.UTF8), new { access_token = "", errcode = 0, errmsg = "" });
                    if (send.errcode > 0) list.Add(new
                    {
                        templateId= mts.template_id,
                        name = x.uiName,
                        openId = x.openId,
                        errcode = send.errcode,
                        errmsg = send.errmsg,
                        poster = poster
                    });
                };
            }
            catch (Exception ex)
            {
                return backJson(1, "解析出错：" + ex.Message, openIdList);
            }
            return backJson(0, null, list);
        }
        /// <summary>
        /// 日程提醒
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult wxScheduleSend()
        {
            var openIdList = Request.Form["openIdList"].xTrim().xUrlDecode();
            var state= Request.Form["state"];
            var url = $"https://api.weixin.qq.com/cgi-bin/token";
            string postData = @"appid={0}&secret={1}&grant_type={2}".jFormat(DefaultValue.AppID, DefaultValue.AppSecret, "client_credential");
            var data = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(Xcode.API.xHttpPostByWebRequest(url, postData, Xcode.ContentType.Form), new { access_token = "", errcode = 0, errmsg = "" });
            if (data.errcode > 0) return backJson(1, data.errmsg);
            var list = new List<userMsg>();
            try
            {
                var json = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(openIdList, new[] { new { openId = "", uiName = "", schTitle="", schDate="", schMark="" } });
                foreach (var x in json)
                {
                    //构建请求数据对象
                    MessageTemplateSendDto mts = new MessageTemplateSendDto
                    {//必填 接收者openid
                        touser = x.openId,
                        //必填 模板ID
                        template_id = "o8Pm8tarzotnvg2Ik2ylj5JSjdrIt8ew9m8r_cXVk2Y",
                        page = $"pages/index/index?user={x.openId}&state={state}",
                        miniprogram_state = "formal",
                        //必填 模板数据
                        data = new MessageTemplateSendDataDto
                        {
                            thing1 = new MessageTemplateSendDataContentDto()
                            {
                                value = x.schTitle,
                                color = "#173177"
                            },
                            time3 = new MessageTemplateSendDataContentDto()
                            {
                                value = x.schDate.xFormatDateTime("yyyy年MM月dd日"),
                                color = "#173177"
                            },
                            thing5 = new MessageTemplateSendDataContentDto()
                            {
                                value = !string.IsNullOrWhiteSpace(x.schMark.xTrim())? x.schMark.xTrim():"...",
                                color = "#173177"
                            }
                        }
                    };
                    string poster = JsonConvert.SerializeObject(mts);


                    var send = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(HttpPostByWebRequest("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + data.access_token, poster, Xcode.ContentType.Json, System.Text.Encoding.UTF8), new { access_token = "", errcode = 0, errmsg = "" });
                    if (send.errcode > 0) list.Add(new userMsg
                    {
                        templateId = mts.template_id,
                        name = x.uiName,
                        openId = x.openId,
                        errcode = send.errcode,
                        errmsg = send.errmsg,
                        poster = poster
                    });
                };
            }
            catch (Exception ex)
            {
                return backJson(1, "解析出错：" + ex.Message, openIdList);
            };
            return backJson(0, null, list);
        }

        public static ResultObj<userMsg> wxScheduleSend_win(string openIdList,string state)
        {
            state = "schedule";
            var result = new ResultObj<userMsg>();

            var url = $"https://api.weixin.qq.com/cgi-bin/token";
            string postData = @"appid={0}&secret={1}&grant_type={2}".jFormat(DefaultValue.AppID, DefaultValue.AppSecret, "client_credential");
            var data = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(Xcode.API.xHttpPostByWebRequest(url, postData, Xcode.ContentType.Form), new { access_token = "", errcode = 0, errmsg = "" });
            if (data.errcode > 0) return result.SetError(data.errmsg);
            try
            {
                var json = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(openIdList, new[] { new { openId = "", uiName = "", schTitle = "", schDate = "", schMark = "" } });
                foreach (var x in json)
                {
                    //构建请求数据对象
                    MessageTemplateSendDto mts = new MessageTemplateSendDto
                    {//必填 接收者openid
                        touser = x.openId,
                        //必填 模板ID
                        template_id = "o8Pm8tarzotnvg2Ik2ylj5JSjdrIt8ew9m8r_cXVk2Y",
                        page = $"pages/index/index?user={x.openId}&state={state}",
                        miniprogram_state = "formal",
                        //必填 模板数据
                        data = new MessageTemplateSendDataDto
                        {
                            thing1 = new MessageTemplateSendDataContentDto()
                            {
                                value = x.schTitle,
                                color = "#173177"
                            },
                            time3 = new MessageTemplateSendDataContentDto()
                            {
                                value = x.schDate.xFormatDateTime("yyyy年MM月dd日"),
                                color = "#173177"
                            },
                            thing5 = new MessageTemplateSendDataContentDto()
                            {
                                value = !string.IsNullOrWhiteSpace(x.schMark.xTrim()) ? x.schMark.xTrim() : "...",
                                color = "#173177"
                            }
                        }
                    };
                    string poster = JsonConvert.SerializeObject(mts);


                    var send = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(HttpPostByWebRequest("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + data.access_token, poster, Xcode.ContentType.Json, System.Text.Encoding.UTF8), new { access_token = "", errcode = 0, errmsg = "" });
                    if (send.errcode > 0) result.ObjList.Add(new userMsg
                    {
                        templateId = mts.template_id,
                        name = x.uiName,
                        openId = x.openId,
                        errcode = send.errcode,
                        errmsg = send.errmsg,
                        poster = poster
                    });
                };
            }
            catch (Exception ex)
            {
                return result.SetError("解析出错：" + ex.Message);
            };
            return result;
        }

        ActionResult userSubscriptionsSetting(List<userMsg> list)
        {
            XElement mediaXML = new XElement("xml");
            try
            {
                foreach (var x in list)
                {
                    mediaXML.Add(new XElement("x",
                            new XElement("templateId", x.templateId),
                            new XElement("name", x.name),
                            new XElement("openId", x.openId),
                            new XElement("errcode", x.errcode),
                            new XElement("errmsg", x.errmsg),
                            new XElement("poster", x.poster)
                        ));
                }
            }
            catch
            {
                return backJson(1, "解析媒体出错");
            };
            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.Exec, DefaultValue.DataBase);
            db.CmdText = "UPDATE FROM dbo.userInfo SET STUFF(subscriptionsSetting, 2, 1, 0) dbo.userInfo WHERE openId IN (@openIdList)";
            db.IsProc = false;
            db.AddParameter("@openIdList", SqlDbType.NVarChar, string.Join(",", list.Select(x => x.openId)),-1);
            db.NeedOutError = true;            
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            return backJson(0, null);
        }
        #endregion

        #region 消息推送配置
        [System.Web.Http.HttpGet]
        [CompressHtml]
        public long getEchostr()
        {
            string signature = Request.QueryString["signature"].xTrim();
            string timestamp = Request.QueryString["timestamp"].xTrim();
            string nonce = Request.QueryString["nonce"].xTrim();
            long echostr = Request.QueryString["echostr"].xTo<long>();
            //可以记录日志查看微信后台传递的参数

            string token = "yangys";
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("token", token);
            dic.Add("timestamp", timestamp);
            dic.Add("nonce", nonce);
            var sortedDict = dic.OrderBy(s => s.Value);
            var conbineStr = "";
            foreach (var s in sortedDict)
            {
                conbineStr = conbineStr + s.Value;
            }
            //sha1加密
            string secret = SHA1(conbineStr, Encoding.UTF8);

            //可以记录日志 检查加密后的参数是否与 signature 一致

            if (secret == signature)
                return echostr;
            else
                return -1;
        }
        /// <summary>
        /// SHA1加密
        /// </summary>
        /// <param name="content"></param>
        /// <param name="encode"></param>
        /// <returns></returns>
        public static string SHA1(string content, Encoding encode)
        {
            try
            {
                System.Security.Cryptography.SHA1 sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
                byte[] bytes_in = encode.GetBytes(content);
                byte[] bytes_out = sha1.ComputeHash(bytes_in);
                sha1.Dispose();
                string result = BitConverter.ToString(bytes_out);
                result = result.Replace("-", "");
                return result.ToLower();
            }
            catch (Exception ex)
            {
                throw new Exception("SHA1加密出错：" + ex.Message);
            }
        }
        #endregion
    }
}